import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList: [],
    userInfo: {}
  },
  mutations: {
    addCart(state, info) {
      // 获取iid查看是否添加过
      const oldInfo = state.cartList.find(item => item.iid == info.iid);
      if (oldInfo) {
        // 如果存在， 把count+1
        oldInfo.count += 1;
      }
      else {
        info.count = 1;
        info.checked = true;
        state.cartList.push(info);
      }
    }
  },
  actions: {
    addCart(context, payload) {
      return new Promise((res, reject) => {
        context.commit('addCart', payload)
        res('添加成功');
      })
    }
  },
  getters: {
    itemNum(state) {
      let num = 0;
      state.cartList.forEach(item => {
        if (item.checked) {
          num++;
        }
      });
      return num;
    }
  },
  modules: {
  }
})
